define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mox/inherit/story/info/index' + location.search,
                    add_url: 'mox/inherit/story/info/add',
                    edit_url: 'mox/inherit/story/info/edit',
                    del_url: 'mox/inherit/story/info/del',
                    multi_url: 'mox/inherit/story/info/multi',
                    import_url: 'mox/inherit/story/info/import',
                    table: 'mox_inherit_story_info',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image },
                        { field: 'era', title: __('Era'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        {
                            field: 'related_persons',
                            title: __('Related_persons'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: function (value, row, index) {
                                if (!value || value == '') {
                                    return '无';
                                }
                                return row.relatedpersons.map((person, i) => {
                                    const imgContainerStyle = `
                                    display: inline-block;
                                    width: 20px;
                                    height: 20px;
                                    border-radius: 10px;
                                    overflow: hidden;
                                    margin-right: 5px;
                                    margin-bottom: 5px;
                                    vertical-align: middle;
                                    `;
                                    const imgStyle = ` width: 100%;height: 100%;object-fit: cover; display: block;`;
                                    const tooltipContent = `<div style="max-width: 300px; max-height: 300px; padding: 10px;">
                                    <div style="display: flex; align-items: start; gap: 10px; ">
                                    ${person.image ? ` <div style="min-width: 60px; height: 60px; border-radius: 10px; overflow: hidden;">
                                        <img src="${person.image}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 10px;">
                                    </div> ` : ''}
                                    <div style="width: 80%;">
                                    <strong>${person.name || '未知'}</strong>
                                    ${person.era ? `<div style="color:#ffffff; font-size:0.9em;">${person.era}</div>` : ''}
                                    ${person.brief_introduction ? `<div style="color:#ffffff; font-size:0.9em; ">${person.brief_introduction}</div>` : ''}
                                    </div></div></div>`;
                                    const uniqueId = `tooltip-${index}-${i}`;
                                    // 绑定 mouseenter 事件，在页面渲染后生效
                                    setTimeout(() => {
                                        $(`#${uniqueId}`).off('mouseenter').on('mouseenter', function () {
                                            layer.tips(tooltipContent, this, {
                                                tips: [1, '#333'],
                                                time: 0,
                                                area: ['auto', 'auto'],
                                                shade: 0,
                                                shadeClose: true,
                                                skin: 'layui-layer-lan'
                                            });
                                        }).off('mouseleave').on('mouseleave', function () {
                                            layer.closeAll('tips');
                                        });
                                    }, 10);
                                    return `<div style="margin: 3px 0; line-height: 1.5;">
                                    ${person.image ? `<span style="${imgContainerStyle}">
                                        <img src="${person.image}" style="${imgStyle}" onerror="this.style.display='none'">
                                        </span>` : ''}
                                        <span id="${uniqueId}" style="cursor: pointer; vertical-align: middle; color: #007bff;">
                                        ${person.name || '未知'}</span></div>`;
                                }).join('');
                            }
                        },
                        // { field: 'content', title: __('Content'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // { field: 'related_persons', title: __('Related_persons'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        {
                            field: 'label',
                            title: __('标签'),
                            formatter: function (value, row, index) {
                                if (!Array.isArray(value)) return '';
                                return value.map((item, idx) => {
                                    return `<span style=" 
                                    display: inline-block;
                                    padding: 2px 6px;
                                    margin-right: 5px;
                                    background-color: ${item.color};
                                    color: #fff;
                                    border-radius: 4px;
                                    font-size: 12px;
                                    ">${item.title}</span>`;
                                }).join('');
                            }
                        },
                        {
                            field: 'chapter_num', title: __('章节管理'), operate: false, table: table, class: 'autocontent',
                            formatter: function (value, row, index) {
                                let num = value > 0 ? `<b style="color: #26ffb6;">（${value}）</b>` : '';
                                return `<a href="mox/inherit/story/chapter/index?s_id=${row.id}" class="btn btn-xs btn-info btn-dialog" data-area="[&quot;95%&quot;,&quot;95%&quot;]" data-shade="[0.5,&quot;#000&quot;]" title="章节管理"><i class="fa fa-list"></i> 章节管理${num}</a>`;
                                // return `<span style="color: #1688f1;font-weight: bold;">${value}</span>`;
                            }
                        },
                        { field: 'zi_num', title: __('总字数') },
                        { field: 'num', title: __('浏览次数') },
                        { field: 'user.nickname', title: __('关联用户') },
                        { field: 'create_time', title: __('Create_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        { field: 'update_time', title: __('Update_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table, events: Table.api.events.operate,
                            // buttons: [
                            //     {
                            //         name: 'detail',
                            //         text: __('章节管理'),
                            //         // title: __('详情'),
                            //         classname: 'btn btn-xs btn-primary btn-dialog',
                            //         // classname: 'btn btn-xs btn-primary btn-addtabs',
                            //         extend: 'data-area=\'["90%","90%"]\'',
                            //         icon: 'fa fa-list',
                            //         url: 'mox/inherit/story/chapter/index?s_id={id}',
                            //     }
                            // ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
